package com.sdgakj.rest;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.sdgakj.common.other.StringUtil;
import com.sdgakj.entity.Family;
import com.sdgakj.entity.FamilyPerson;
import com.sdgakj.entity.Person;
import com.sdgakj.service.account.ShiroDbRealm;
import com.sdgakj.service.family.FamilyService;
import com.sdgakj.service.person.PersonService;
import com.sdgakj.service.user.UserService;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 家族的Restful API的controller
 *
 * @author eiffel
 */
@RestController
@RequestMapping(value = "/api/v1/family")
public class FamilyRestController {
    private static Logger logger = LoggerFactory.getLogger(FamilyRestController.class);

    @Autowired
    private FamilyService familyService;

    @Autowired
    private UserService userService;

    @Autowired
    private PersonService personService;

    private static final String PAGE_SIZE = "10";

    private static Map<String, String> sortTypes = Maps.newLinkedHashMap();

    /**
     * 家族列表
     * @param pageNumber
     * @param pageSize
     * @param sortType
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject showTree(
            @RequestParam(value = "page", defaultValue = "1") int pageNumber,
            @RequestParam(value = "pageSize", defaultValue = PAGE_SIZE) int pageSize,
            @RequestParam(value = "sortType", defaultValue = "auto") String sortType) {
        JSONObject result = new JSONObject();
        logger.info("query the family list...");
        Map<String, Object> searchParams =new HashMap<>();
        Page<Family> families =null;
        families = familyService.getFamilis(searchParams, pageNumber, pageSize, sortType);
        result.put("families",families);
        result.put("sortType", sortType);
        result.put("sortTypes", sortTypes);
        return result;
    }

    /**
     * 修改家族信息
     * @param id
     * @param fName
     * @param fDesp
     * @return
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject updateFamily( @RequestParam(value = "id") Long id,
                                    @RequestParam(value = "userId") Long userId,
                                @RequestParam(value = "fName") String fName,
                                @RequestParam(value = "fDesp") String fDesp) {
        logger.info("update the family...");
        JSONObject result = new JSONObject();
        //根据id查出家族数据后，更新家族名、描述、更新时间
        Family familyById = familyService.getFamilyById(id);
        Timestamp tsu = new Timestamp(new Date().getTime());
        familyById.setUpdatetime(tsu);
        familyById.setfName(fName);
        familyById.setfDesp(fDesp);
        familyById.setUserId(userId);
        familyService.updateFamily(familyById);
        result.put("message", "修改成功！");
        return result;

    }

    /**
     * 删除家族信息
     * @param id
     * @return
     */
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    @ResponseBody
    public JSONObject delete( @RequestParam(value = "id") Long id) {
        familyService.deleteFamily(id);
        JSONObject result = new JSONObject();
        result.put("message", "删除成功！");
        return result;
    }

    /**
     * 添加家族信息
     * @param fName
     * @param fDesp
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject createFamily(@RequestParam(value = "fName") String fName,
                                   @RequestParam(value = "fDesp") String fDesp,
                                   @RequestParam(value = "userId",required = false) Long userId) {
        logger.info("save the family");
        JSONObject result = new JSONObject();
        Family entity=new Family();
        entity.setfName(fName);
        entity.setfDesp(fDesp);
        Timestamp tsu = new Timestamp(new Date().getTime());
        entity.setCreatetime(tsu);
        entity.setUpdatetime(tsu);
        entity.setUserId(userId);
        familyService.saveFamily(entity);
        result.put("message", "添加成功！");
        return result;
    }
    /*
    *
    * 通过个人页面删除亲属
    * */
    @RequestMapping(value = "/deleteperson", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject deletePerson(@RequestParam(value = "userId")Long userId,
                                   @RequestParam(value = "familyId")Long familyId,Long relationId){
        JSONObject request=new JSONObject();
        try {
            Person user = personService.getPersonByUserId(userId);
            Person familyPerson = personService.getPersonById(familyId);
            if (user != null && familyPerson != null) {
                //1父母，2妻子丈夫，3兄弟姐妹，4孩子
                if (relationId == 1L) {
                    //删除父母
                    if (familyPerson.getS().equals("M")) {
                        //表示是父亲
                        if (user.getF() == familyPerson.getId()) {
                            //表示相同，把user的f字段变更为0
                            user.setF(0L);
                            personService.updatePersonById(user);
                        }
                    } else {
                        if (user.getM() == familyPerson.getId()) {
                            user.setM(0L);
                            personService.updatePersonById(user);
                        }
                    }
                }
                if (relationId == 2L) {
                    //妻子、丈夫
                    if (familyPerson.getS().equals("M")) {
                        //丈夫
                        if (user.getVir() == familyPerson.getId()) {
                            user.setVir(0L);
                            personService.updatePersonById(user);
                        }
                    } else {
                        if (user.getUx() == familyPerson.getId()) {
                            user.setUx(0L);
                            personService.updatePersonById(user);
                        }
                    }
                }
                if (relationId == 3L || relationId == 4L) {
                    //兄弟姐妹,把父母的id改为0,删除孩子也是把孩子的父母id设为0
                    familyPerson.setF(0L);
                    familyPerson.setM(0L);
                    personService.updatePersonById(familyPerson);
                }
            }
            request.put("mess", "删除成功");
        }catch (Exception e){
            request.put("mess","删除失败");
        }

        return request;
    }


}
